package com.project.class4_7;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RWTest {
    //创建读写锁对象
    private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    public void read1(){
        //加读锁
        rwlock.readLock().lock();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("读锁："+Thread.currentThread() + "  "+i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally{
            //释放读锁
            rwlock.readLock().unlock();
        }
    }

    public void read2(){
        //加读锁
        rwlock.readLock().lock();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("读锁："+Thread.currentThread() + "  "+i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally{
            //释放读锁
            rwlock.readLock().unlock();
        }
    }

    public void write(){
        //加写锁
        rwlock.writeLock().lock();
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println("写锁："+Thread.currentThread() + "  "+i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally{
            //释放写锁
            rwlock.writeLock().unlock();
        }
    }
}
